﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;
using System.ComponentModel;

namespace IronCow.Posh.Commands
{
    [Cmdlet(VerbsDiagnostic.Test, "RtmAuthenticationToken")]
    [System.ComponentModel.Description("Tests whether the user is authenticated with RTM.")]
    public class TestRtmAuthenticationTokenCommand : RtmCmdlet
    {
        [Parameter(
            Position = 1,
            ValueFromPipeline = true,
            HelpMessage = "The token to test.")]
        [ValidateNotNullOrEmpty]
        [Alias("Value")]
        [DefaultValue(null)]
        public string Token { get; set; }

        protected override void BeginProcessing()
        {
            try
            {
                if (string.IsNullOrEmpty(Token))
                    Token = Properties.Settings.Default.Token;
                if (string.IsNullOrEmpty(Token))
                    throw new PSArgumentException("No authentication token was specified, and none was stored in the user settings.");
            }
            catch (PSArgumentException ex)
            {
                ThrowTerminatingError(new ErrorRecord(ex, "NoAuthenticationTokenFound", ErrorCategory.InvalidOperation, null));
            }
        }

        protected override void ProcessRecord()
        {
            Authentication authentication;
            if (Rtm.CheckToken(Token, out authentication))
            {
                WriteObject(true);
            }
            else
            {
                WriteObject(false);
            }
        }
    }
}
